<template>
  <div id="contentRight">
    <section id="sec1">
      <p class="guide">
        <router-link to="/asset">资产总览&nbsp;&nbsp;>&nbsp;</router-link>
        <span>提币</span>
      </p>
      <p class="title p2">选择提币类型</p>
      <div class="d3">
        <button v-for="(item , index) in coinList"
                @click="outCoinName = item.value" :class="item.value === outCoinName ? 'active' :''">{{item.name}}</button>
      </div>
      <p class="p4 title">提币数量</p>
      <p class="p5">
        <input type="number" v-model="num" placeholder="请输入提币数量" @blur="num = num < 0  ? coinMinNum : num">
        <span>可用余额：{{coinLeast}} {{outCoinCnName}}</span>
        <span class="inputAll hoverhand" @click="num = coinLeast">全部</span>
      </p>
      <p class="title p6">选择提币方式</p>
      <div class="d7">
        <label for="bhpay">
          <input type="radio" name="outType" value="0" id="bhpay" v-model="outType">
          <span class="name">我的BHPay钱包<span>（ 无需手续费）</span></span>
        </label>
        <label for="otherWallet" v-if="outCoinName != 'BHP_FH'">
          <input type="radio" name="outType" value="1" id="otherWallet" v-model="outType">
          <span class="name">其他数字钱包</span>
        </label>
      </div>
      <div class="bhpayWallet" v-if="outType == 0">
        <p class="p1" v-if="!bhpayData">
          <span @click="relationBHpay">关联BHPay钱包</span>
        </p>
        <div class="bhpayData" v-if="bhpayData">
          <p class="p1">{{bhpayData.name}}</p>
          <p class="p2">
            <span>{{bhpayData.card_num}}</span>
            <a :href="bhpayData.down_uri" target="_blank">下载bhpay钱包 > </a>
          </p>
        </div>
      </div>
      <div class="otherWallet" v-if="outType == 1 && outCoinName !='BHP_FH'">
        <p class="address">提币地址</p>
        <div class="d1">
          <el-select v-model="selAddress" :placeholder="addressPlaceholder" class="leftValue">
            <el-option
              v-for="item in addressList" :key="item.id" :label="item.wallet_address" :value="item.id">
            </el-option>
          </el-select>
          <router-link to="/addressManage">提币地址管理</router-link>
        </div>
      </div>
      <p class="p10 title" v-if="outType == 1">手续费</p>
      <p class="p11" v-if="outType == 1">
        <span>{{serviceCharge}}</span><span>{{outCoinName}}</span>
      </p>
      <div class="d12 reminder">
        <p>提示：</p>
        <div>
          1.最小提币数量为{{outType == 0 ? coinMinNum : otherWalletMsg.repurchaseMin}}{{outCoinCnName}}<br>
          2. 提笔手续费为矿工费，RR Mine不会收取您的费用<br>
          3. 提必请务必保证提币地址的准确性，否则资产将无法找回<br>
          4. 后台审核后一般0~60分钟到账，因网络原因有可能延迟<br>
          5. 如长时间未到账，请联系客服核查<br>
          6. BHPay不收取手续费
        </div>
      </div>
      <p class="p12">
        <button @click="applyOut()">申请提币</button>
      </p>
    </section>
    <confirm-dialog ref="openapp" :msg="openAppInfo"></confirm-dialog>
    <confirm-dialog ref="needSetPws" :msg="needSetPws" @click="this.$router.push({path : '/setPws'})"></confirm-dialog>
    <get-phonecode ref="outCoinsVerfiyCode" @confirm="outCoinsPost" :openPhoneCode="1" :openTransPws="1"></get-phonecode>
    <outcoin-dangelog ref="outcoinDanger" @cancel="outType = 0"/>
<!--    <confirm-dialog ref="dl" v-bind:msg="safeInfo" @confirm="sure()"></confirm-dialog>-->
  </div>
</template>
<script>
  import {bhpayMes, myAssets, otherAddressList , outCoinsMinNum , isSetTransactionPws, outCoinsToBhpay , outCoinsToOther} from '../http/api';
  export default {
    name : 'outCoins',
    inject : ['reload'],
    data(){
      return{
        coinList : [
          { value : 'BTC' , name :'BTC' } , { name : 'ETH',value : 'ETH' }, { name : 'LTC',value : 'LTC' },
          { name : 'BHP(交易账户)',value : 'BHP' } , { name : 'BHP(分红账户)',value : 'BHP_FH' },{ name : 'USDT',value : 'USDT' },
        ],
        outCoinName : 'BTC' , //币种
        outCoinCnName : 'BTC', //可用余额显示的币种中文名
        coinMinNum : 0,//最低提币数量
        num : null,//提币数量
        outType : 0 ,//提币钱包
        coinsList : {},//币种余额对象
        coinLeast :  '',//币种余额
        serviceCharge : '0.000000',//手续费
        openBhpay : false,//是否关联bhpay
        bhpayData : null, //bhpay信息
        addressList : [],//提币地址列表
        selAddress : '',//选择的提币地址
        addressPlaceholder : '',//提币地址placeholder
        otherWalletMsg : {},//其他钱包的信息
        isSetPws : false,//是否设置交易密码
        verFyCode : null,
        safeInfo : require('../common/jsons/text').cashWithDrawVerification.html,//实名安全提示文字
        openAppInfo : require('../common/jsons/text').openBHpayToApp.html,//需要打开app操作
        needSetPws : require('../common/jsons/text').needSetPws.html, //需要设置交易密码
      }
    },
    components:{
      ElSelect :  require('element-ui').Select, /*select*/
      ElOption : require('element-ui').Option, /*Option*/
      ConfirmDialog : resolve => { require(['../components/ConfirmDialog'], resolve) },/*确认弹窗*/
      GetPhonecode : resolve => { require(['../components/GetMbcode'], resolve) },/*提现验证弹窗*/
      OutcoinDangelog : resolve => { require(['../components/OutCoinDangerReminder'], resolve) },/*提现验证弹窗*/
    },
    mounted(){
      let thiz = this;
      function getUrlKey(name , url){
        return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ""])[1].replace(/\+/g, '%20')) || null;
      }
      let coin = getUrlKey("coin", window.location.href) || null;//判断是否有设置币种
      let Not = {noToast: true, noLoading: true};
      var https = [
        bhpayMes(Not).then( res => {
          thiz.openBhpay = res.code == 200 ? true : false;
          if( res.code == 200 ){
            let data = res.data || false;
            if( data && JSON.stringify(data) != '{}' ){
              thiz.openBhpay = true;
              var card_num = data.card_num;
              var reg = /^(\d{4})\d{8}(\d{4})$/;
              data.card_num = card_num.replace(reg, '$1********$2');
              thiz.bhpayData = data;
            } else{
              thiz.openBhpay = false;
            }
          }else{
            thiz.openBhpay = false;
          }
        }),
        myAssets(Not).then(res => {
          if(res.code == 200){
            let coinsList = res.data.res.assets_lists;
            this.coinsList = coinsList;
            this.coinLeast =coinsList[this.outCoinName].coin;
            thiz.outCoinName = coin.toUpperCase();
          }
        }),
        isSetTransactionPws(Not).then( res => {
          thiz.isSetPws =  Number(res.code) === 344 ? false : true;
        }),
        this.getOutCoinsAddress(true)
      ];
      this.PromiseAll(https , res => {
        if(thiz.verFyCode == 2){
          this.$router.push({path: '/verFyCode', query: {rechargeVerify: true}});
        }
      })
    },
    watch:{
      'num'( num ){
        if(num > this.coinLeast ){
          this.num = this.coinLeast;
        }
      },
      'outCoinName'(name){
        this.num = '';
        this.outType = name === 'BHP_FH' ? 0 : this.outType;
        this.coinLeast = this.coinsList[this.outCoinName].coin;
        let thiz = this , coinList = thiz.coinList;
        this.for(coinList ,(item , index)=>{
          if(name === item.value){
            thiz.outCoinCnName = item.name;
          }
        });
        this.getOutCoinsAddress();
      },
      'outType'(type){
        this.getOutCoinsAddress();
        if(type == 1){
          this.$refs.outcoinDanger.show();
        }
      }
    },
    methods:{
      applyOut(){
        let outType = this.outType;
        let minNum = outType == '0' ? this.coinMinNum : this.otherWalletMsg.repurchaseMin;
        if( !this.isSetPws ){
          this.$refs.needSetPws.dialogShow();
        }else if( !this.num || Number(this.num) < minNum) {
          require('../common/js/toast').toast(`提币数量不能小于${minNum}`);
        }else{
          this.$refs.outCoinsVerfiyCode.dialogShow();
        }
      },
      outCoinsPost( verfilyRes ){
        //post提交数据
        let thiz = this;
        switch (Number(this.outType)) {
          //提币bhpay
          case 0 :
            let param = {
              currency_name: this.outCoinName,
              num: this.num,
              smscaptcha: verfilyRes.code ,
              trade_password: verfilyRes.pws
            };
            outCoinsToBhpay(param).then(res => {
              if(res.code == 200){
                require('../common/js/toast').toast('提币至BHpay成功');
                this.$refs.outCoinsVerfiyCode.hide();
                thiz.timeout(function () {
                  thiz.reload();
                },1500)
              }
            });
            break;
          case 1 :
            let selAddress = thiz.selAddress;
            let addressList = thiz.addressList;
            let param2 = {
              wallet_address: null,
              coin_type: thiz.outCoinName,
              coin_num: thiz.num,
              smscaptcha: verfilyRes.code ,
              trade_password: verfilyRes.pws
            };
            thiz.for(addressList,(item,index) => {
              if(item.id == selAddress){
                param2.wallet_address = item.wallet_address;
              }
            });
            outCoinsToOther(param2).then(res => {
              if(res.code == 200){
                require('../common/js/toast').toast(`提币成功`);
                this.$refs.outCoinsVerfiyCode.hide();
                thiz.timeout(function () {
                  thiz.reload();
                },1500)
              }
            });
            break;
        }
      },
      getOutCoinsAddress( noLoading ){
        //获取提币地址列表  拿取最小提币数量
        if(this.outType == 1 && this.addressList.length === 0){
          otherAddressList({currency_code : this.outCoinName }).then(res => {
            if(res.code == 200){
              let lists = res.data.lists;
              console.log('lists',lists)
              this.addressList = lists;
              if(lists.length > 0){
                this.selAddress = lists[0].id;
              }
              this.addressPlaceholder = lists.length > 0 ? '请选择提币地址' : '暂未添加提币地址';
            }
          });
        }
        let thiz = this;
        let param = {
          coin_code: thiz.outCoinName == "BHP_FH" ? "BHP" : thiz.outCoinName
        };
        if(noLoading){
          param.noLoading = true;
          param.noToast = true;
        }
       return outCoinsMinNum(param).then(res => {
          if(res.code == 200){
            thiz.coinMinNum = res.data.bhpay;
            thiz.otherWalletMsg = res.data.other;
            thiz.serviceCharge = res.data.other.withdrawCoinFee
          }
        })
      },
      relationBHpay(){
        //提示到app去关联
        this.$refs.openapp.dialogShow();
      }
    }
  }
</script>
<style lang="less" scoped>
  @import "../common/style/common";
  @import "../common/style/public.css";
  #sec1{
    min-height: 725px;padding-bottom: 40px;
    >.title{
      color: #999;font-size: 14px;
      &.p2{
        padding-top: 59px;
      }
    }
    >.d3{
      overflow: hidden;width: 65%;
      >button{
        float: left;width: 146px;height: 48px;font-size: 18px;color: #262626;.borderRadius;margin-left: 20px;background: #F8F8F8;margin-top: 14px;
        &:nth-child(4n+1){
          margin-left: 0;
        }
        &.active{
          .colorYellow;background: url("../common/imgs/coincheckedbg.png") center center no-repeat;background-size: 100% 100%;
        }
        &:hover{
          .colorYellow;
        }
      }
    }
    >.p4{
      padding-top: 24px;
    }
    >.p5{
      overflow: hidden;padding-top: 13px;
      input{
        .input;width: 463px;height: 40px;padding: 0 9px;
      }
      >span{
        line-height: 40px;color: #666666;
        &:nth-child(2){
          padding-left: 21px;
        }
        &.inputAll{
          .colorYellow;padding-left: 15px;
        }
      }
    }
    >.p6{
      padding-top: 25px;
    }
    >.d7{
      overflow: hidden;padding-top: 15px;
      >label{
        float: left;display: inline-block;position: relative;
        >input{
          opacity: 0;position: absolute;z-index: 1;left: 0;top:0;width: 100%;height: 100%;
          &:hover{
            cursor: pointer;
          }
        }
        &:nth-child(2){
          margin-left: 128px;
        }
        >span{
          position: relative;padding-left: 20px;line-height: 16px;display: inline-block;height: 16px;color: #666;
          >span{
            display: contents;.colorYellow;
          }
          &:before{
            content: '';display: inline-block;width: 14px;height: 14px;border-radius: 50%;border:1px solid#666;
            position: absolute;left: 0;top:50%;margin-top: -7px;box-sizing: border-box;
          }
        }
        >input:checked+span:before{
          content: '';display: inline-block;border:none;background: url("../common/imgs/checkedradios.png") center center no-repeat;background-size: 100% 100%;
        }
      }
    }
    >.bhpayWallet{
      >.p1{
        padding-top: 16px;
        >span{
          display: inline-block;background-color: #3574FA;font-size: 16px;color: #fff;width: 160px;text-align: center;height: 38px;line-height: 38px;.borderRadius;
          &:hover{
            cursor: pointer;
          }
        }
      }
      >.bhpayData{
        background: url("../common/imgs/newimgoutcoin.png") center center no-repeat;background-size: 100% 100%;width: 462px;
        margin-top: 25px;
        a{
          color: rgba(75, 62, 49, 0.68);font-size: 14px;float: right;
        }
        >.p1{
          padding: 15px ;
        }
        >.p2{
          overflow: hidden;padding:0 15px ;padding-bottom: 15px;
        }
      }
    }
    >.otherWallet{
      >.address{
        color: #999;font-size: 14px;padding: 15px 0;padding-top: 24px;
      }
      >.d1{
        >a{
          display: inline-block;height: 40px;line-height: 40px;.colorYellow;margin-left: 21px;
        }
      }
    }
    >.p10{
      padding-top: 42px;
    }
    >.p11{
      width: 462px;height: 40px;background: #F8F8F8;padding: 0 15px;margin-top: 15px;
      >span{
        line-height: 40px;color: #262626;
        &:last-child{
          float: right;
        }
      }
    }
    >.reminder{
      color: #999999;font-size: 14px;
      >p{
        padding-top: 28px;padding-bottom: 10px;
      }
      >div{
        line-height: 170%;
      }
    }
    >.p12{
      padding-top: 37px;
      button{
        .submit;width: 160px;height: 40px;line-height: 40px;font-size: 16px;
      }
    }
  }
</style>
